<?php
class YouNet_Storage_S3 implements YouNet_Storage_Interface 
{
	private $_s3;
	private $_bucket;
	private $_prefix = '';
	private $_default_meta = array(
		'Cache-Control' => 'public, max-age=2592000'
	);
	
	public function __construct($options)
	{
		$this->_s3 = new Zend_Service_Amazon_S3($options['key'], $options['secret']);
		$this->_bucket = $options['bucket'];
		$this->_prefix = $this->_bucket;
	}
	
	public function put($filename, $data, $privacy = self::PRIVACY_PUBLIC)
	{
		$filename = str_replace("\\", "/", $filename);
		return $this->_s3->putObject($this->_prefix . $filename
                , $data
                , $this->_generateMetaFromPrivacy($privacy));
	}
	
	public function get($filename)
	{		
		return $this->_s3->getObject($this->_prefix . $filename);
	}
	
	public function remove($filename)
	{		
		return $this->_s3->removeObject($this->_prefix . $filename);
	}
    
    public function copy($source, $dest, $privacy = self::PRIVACY_PUBLIC)
	{		
        
		return $this->_s3->copyObject($this->_prefix . $source
            , $this->_prefix . $dest
            , $this->_generateMetaFromPrivacy($privacy));
	}
	
	public function copyToLocal($source, $dest)
	{	
		return file_put_contents($dest, $this->get($source));
	}
    
    private function _generateMetaFromPrivacy($privacy)
    {
        $meta = $this->_default_meta;
        if ($privacy == self::PRIVACY_PUBLIC)
        {
            $meta = array_merge($meta, array(Zend_Service_Amazon_S3::S3_ACL_HEADER =>
		          Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ));
		} 
        return $meta;
    }
}